package com.exposit.zbs.controller;

import com.exposit.zbs.model.GrantChangelog;
import com.exposit.zbs.model.Message;
import com.exposit.zbs.model.User;
import com.exposit.zbs.service.IGrantApplicationService;
import com.exposit.zbs.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;


/**
 * Created by Andrey on 20.08.2014.
 */
@Controller
@RequestMapping("/my")
public class MyController {

	@Autowired
	private IGrantApplicationService grantApplicationService;

	@Autowired
	private IUserService userService;

	@RequestMapping(value = "/feed", method = RequestMethod.GET)
	public ModelAndView getUserFeed(HttpSession session) {

		ModelAndView mav = new ModelAndView("my.feed");
		Object userObject = session.getAttribute("sessionUser");
		if (userObject instanceof User) {
			User currentUser = (User) userObject;
			List<GrantChangelog> feed = grantApplicationService.getUsersFeed(currentUser);
			if (feed != null) {
				mav.addObject("feed", feed);
			}
		}
		return mav;
	}
	@RequestMapping(value = "/messages", method = RequestMethod.GET)
	public ModelAndView getUserMessages(HttpSession session){
		ModelAndView mav = new ModelAndView("my.messages");
		Object userObject = session.getAttribute("sessionUser");
		if (userObject instanceof User) {
			User currentUser = (User) userObject;
			User updatedUser = userService.getUserbyId(currentUser.getUserId());
			userService.readMessages(updatedUser);
			mav.addObject("currentUser", updatedUser);
		}
		return mav;
	}

	@RequestMapping(value = "/message/send/{userId}", method = RequestMethod.POST)
	public ModelAndView sendMessage(@PathVariable String userId, @PathVariable("userId") User reciever, String messageText, HttpSession session) {

		ModelAndView mav = new ModelAndView("redirect:/my/messages");
		Object userObject = session.getAttribute("sessionUser");
		if (userObject instanceof User) {
			User currentUser = (User) userObject;
			Message message = new Message();
			message.setMessageText(messageText);
			message.setMessageDate(new Date());
			message.setSender(currentUser);
			message.setReciver(reciever);
			message.setReaded(false);
			userService.sendMessage(message);
		}
		return mav;
	}
}
